<template>
  <div class="container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ questionsForm.id? '试题修改' :'试题录入'}}</span>
      </div>
      <el-form :model="questionsForm" :rules="rules" ref="questionsForm">
        <el-form-item label-width="100px" label="学科：" prop="subjectID">
          <el-select
            v-model="questionsForm.subjectID"
            placeholder="请选择"
            style="width: 400px"
            @change="simplesChange"
          >
            <el-option
              v-for="item in simples"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label-width="100px" label="目录：" prop="catalogID">
          <el-select
            v-model="questionsForm.catalogID"
            placeholder="请选择"
            style="width: 400px"
          >
            <el-option
              v-for="item in catalogs"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label-width="100px" label="企业：" prop="enterpriseID">
          <el-select
            v-model="questionsForm.enterpriseID"
            placeholder="请选择"
            style="width: 400px"
          >
            <el-option
              v-for="item in companyslist"
              :key="item.id"
              :label="item.company"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label-width="100px" label="城市：" prop="province">
          <el-select
            v-model="questionsForm.province"
            placeholder="请选择"
            style="width: 195px; margin-right: 10px"
            @change="provinceChange"
          >
            <el-option
              v-for="item in datas"
              :key="item.city"
              :label="item.city"
              :value="item.city"
            >
            </el-option>
          </el-select>
          <el-select
            v-model="questionsForm.city"
            placeholder="请选择"
            style="width: 195px"
          >
            <el-option
              v-for="item in areas"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label-width="100px" label="方向：" prop="direction">
          <el-select
            v-model="questionsForm.direction"
            placeholder="请选择"
            style="width: 400px"
          >
            <el-option
              v-for="item in direction"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label-width="100px" label="题型：" prop="questionType">
          <el-radio-group v-model="questionsForm.questionType">
            <el-radio
              v-for="item in questionType"
              :key="item.value"
              :label="item.value"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label-width="100px" label="难度：" prop="difficulty">
          <el-radio-group v-model="questionsForm.difficulty">
            <el-radio
              v-for="item in difficulty"
              :key="item.value"
              :label="item.value"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label-width="100px"
          label="题干："
          style="height: 200px"
          prop="question"
        >
          <quillEditor
            v-model="questionsForm.question"
            :options="editorOption"
            style="height: 150px"
          />
        </el-form-item>
        <el-form-item
          label-width="100px"
          label="选项："
          v-if="questionsForm.questionType !== '3'"
        >
          <template v-if="questionsForm.questionType === '1'">
            <div
              class="options_item"
              v-for="item in questionsForm.options"
              :key="item.code"
            >
              <el-radio
                :label="item.code"
                v-model="radioOptions"
                @input="optionRadio"
              >
                {{ item.code }}：
                <el-input v-model="item.title"></el-input>
              </el-radio>
              <QuestionsUpload :item="item" />
            </div>
          </template>
          <template v-if="questionsForm.questionType === '2'">
            <div
              class="options_item"
              v-for="item in questionsForm.options"
              :key="item.code"
            >
              <el-checkbox-group v-model="checkList" @change="optionCheck">
                <el-checkbox :label="item.code">
                  {{ item.code }}：
                  <el-input v-model="item.title"></el-input>
                </el-checkbox>
              </el-checkbox-group>
              <QuestionsUpload :item="item" />
            </div>
          </template>
          <div>
            <el-button
              type="danger"
              size="small"
              @click="addOptions"
              :disabled="isDisabled"
              >+增加选项与答案</el-button
            >
          </div>
        </el-form-item>
        <el-form-item label-width="100px" label="视频解析：">
          <el-input
            placeholder="请输入内容"
            v-model="questionsForm.videoURL"
            style="width: 400px"
            clearable
          >
          </el-input>
        </el-form-item>
        <el-form-item
          label-width="100px"
          label="答案解析："
          style="height: 200px"
          prop="answer"
        >
          <quillEditor
            v-model="questionsForm.answer"
            :options="editorOption"
            style="height: 150px"
          />
        </el-form-item>
        <el-form-item label-width="100px" label="题目备注：">
          <el-input
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
            placeholder="请输入内容"
            v-model="questionsForm.remarks"
            style="width: 400px"
          >
          </el-input>
        </el-form-item>
        <el-form-item label-width="100px" label="试题标签：" prop="tags">
          <el-select
            v-model="questionsForm.tags"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择试题标签"
          >
            <el-option
              v-for="item in tags"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="margin-left: 100px">
          <el-button type="primary" @click="onSubmit">确认提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
// 富文本样式
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import QuestionsUpload from '../components/questions-upload.vue'
import { quillEditor } from 'vue-quill-editor'
import { list as companysList } from '@/api/hmmm/companys.js'
import { simple as getUserid } from '@/api/base/users.js'
import { simple } from '@/api/hmmm/subjects.js'
import { simple as getCatalogID } from '@/api/hmmm/directorys.js'
import { simple as getTags } from '@/api/hmmm/tags.js'
import { difficulty, direction, questionType } from '@/api/hmmm/constants.js'
import { datas } from '@/api/hmmm/citys.js'
import { add, detail, update } from '@/api/hmmm/questions.js'
// 富文本设置
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
  [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
  ['blockquote'], // 引用  代码块
  ['clean'], // 清除文本格式
  ['code-block', 'link', 'image'] // 链接、图片、视频
]
// 验证表单
const rules = {
  subjectID: [{ required: true, message: '请选中学科' }],
  catalogID: [{ required: true, message: '请选中目录' }],
  enterpriseID: [{ required: true, message: '请选中企业' }],
  province: [{ required: true, message: '请选中城市' }],
  direction: [{ required: true, message: '请选中方向' }],
  questionType: [{ required: true, message: '请选中题型' }],
  difficulty: [{ required: true, message: '请选中难度' }],
  question: [{ required: true, message: '请输入题干' }],
  tags: [{ required: true, message: '请选中试题标签' }],
  answer: [{ required: true, message: '请输入答案解析' }]
}
export default {
  components: { quillEditor, QuestionsUpload },
  data () {
    return {
      questionsForm: {
        subjectID: '', // 学科
        direction: '', // 方向
        difficulty: '1', // 难度
        questionType: '1', // 试题类型
        catalogID: '', // 目录
        city: '', // 城市
        province: '', // 省份
        enterpriseID: '', // 企业
        question: '', // 题干
        answer: '', // 答案解析
        remarks: '', // 题目备注
        videoURL: '', // 视频解析
        options: [
          { isRight: false, code: 'A', title: '', img: '' },
          { isRight: false, code: 'B', title: '', img: '' },
          { isRight: false, code: 'C', title: '', img: '' },
          { isRight: false, code: 'D', title: '', img: '' }
        ],
        tags: [] // 标签
      },
      simples: [], // 学科内容
      tags: [], // 标签
      catalogs: [], //  二级目录
      difficulty, // 难度
      questionType, // 试题类型
      direction, // 方向
      creator: [], // 录入人
      datas, // 城市
      areas: [], // 区
      companyslist: [], // 企业
      editorOption: {
        // 富文本设置
        theme: 'snow', // or 'bubble'
        placeholder: '请输入文章内容',
        modules: {
          toolbar: {
            container: toolbarOptions
          }
        }
      },
      englishArr: [], // 字母
      radioOptions: '', // 单选框
      checkList: [], // 复选框
      rules // 表单校验
    }
  },
  created () {
    this.getSimple()
    this.getEnginsh()
    this.isOpations()
    if (this.$route.query.id) {
      this.getInfo()
    }
  },
  computed: {
    isDisabled () {
      if (this.englishArr.length === 0) return true
      return false
    }
  },
  beforeDestroy () {
    this.questionsForm = {
      subjectID: '', // 学科
      direction: '', // 方向
      difficulty: '1', // 难度
      questionType: '1', // 试题类型
      catalogID: '', // 目录
      city: '', // 城市
      province: '', // 省份
      enterpriseID: '', // 企业
      question: '', // 题干
      answer: '', // 答案解析
      remarks: '', // 题目备注
      videoURL: '', // 视频解析
      options: [
        { isRight: false, code: 'A', title: '', img: '' },
        { isRight: false, code: 'B', title: '', img: '' },
        { isRight: false, code: 'C', title: '', img: '' },
        { isRight: false, code: 'D', title: '', img: '' }
      ],
      tags: [] // 标签
    }
  },
  methods: {
    // 获取学科列表
    async getSimple () {
      const { data } = await simple()
      this.simples = data
      const { data: creator } = await getUserid()
      this.creator = creator
      const { data: dataitem } = await companysList()
      this.companyslist = dataitem.items
    },
    // 获取联动数据
    async simplesChange () {
      const { data: catalogs } = await getCatalogID({
        subjectID: this.questionsForm.subjectID
      })
      const { data: tags } = await getTags({
        subjectID: this.questionsForm.subjectID
      })
      this.catalogs = catalogs
      this.tags = tags
    },
    // 城市
    provinceChange () {
      this.areas =
        datas.find(item => item.city === this.questionsForm.province)?.area ||
        []
    },
    // 确认提交
    async onSubmit () {
      try {
        await this.$refs.questionsForm.validate()
        if (this.questionsForm.id) {
          await update({ ...this.questionsForm, tags: this.questionsForm.tags.join(', ') })
          this.$message.success('编辑成功')
        } else {
          await add({ ...this.questionsForm, tags: this.questionsForm.tags.join(', ') })
          this.$message.success('添加成功')
        }
        this.$router.push('/questions/list')
      } catch (e) {
        console.log(e)
      }
    },
    // 获取随机英文字母
    getEnginsh () {
      for (let i = 69; i < 91; i++) {
        this.englishArr.push(String.fromCharCode(i))
      }
    },
    // 添加选项
    addOptions () {
      const i = 0
      this.questionsForm.options.push({
        isRight: false,
        code: this.englishArr[i],
        title: '',
        img: ''
      })
      this.englishArr = this.englishArr.slice(i + 1)
      if (!this.englishArr.length) return
      console.log(this.englishArr)
    },
    // 单选框逻辑
    optionRadio (val) {
      this.questionsForm.options.forEach(item => {
        if (item.code === val) {
          item.isRight = true
        } else {
          item.isRight = false
        }
      })
    },
    // 复选框
    optionCheck (val) {
      this.questionsForm.options.forEach(item => {
        if (val.includes(item.code)) {
          item.isRight = true
        } else {
          item.isRight = false
        }
      })
    },
    // 判断选项是否有值
    isOpations () {
      const res = this.questionsForm.options.filter(item => item.isRight)
      if (res.length === 1) {
        this.radioOptions = res[0].code
      } else {
        res.forEach(item => this.checkList.push(item.code))
      }
    },
    // 处理路由跳转过来的数据
    async getInfo () {
      console.log(1)
      const { data } = await detail({ id: this.$route.query.id })
      this.questionsForm = { ...data, tags: data.tags?.split(',') || [] }
    }
  }
}
</script>

<style scoped lang='less'>
  .container {
    margin: 10px 0;
    padding: 0 10px;
    .options_item {
      display: flex;
      align-items: center;
      margin-bottom: 20px;
      // /deep/ .el-radio__label {
      //   display: flex;
      //   align-items: center;
      // }
    }
  }
</style>
